package com.client.qiuqiu;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.client.qiuqiu.adapters.FriendsAdapter;
import com.client.qiuqiu.databinding.FragmentFriendListBinding;
import com.client.qiuqiu.listeners.Userlistener;

import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FriendListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FriendListFragment extends Fragment implements Userlistener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private List<Friend> friends = new ArrayList<>();
    private FragmentFriendListBinding binding;
    Handler mainHandler,workHandler;
    HandlerThread mHandlerThread;

    public FriendListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FriendListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FriendListFragment newInstance(String param1, String param2) {
        FriendListFragment fragment = new FriendListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentFriendListBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    //绑定控件
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 创建与主线程关联的Handler
        mainHandler = new Handler();
        mHandlerThread = new HandlerThread("handlerThread");
        //启动线程
        mHandlerThread.start();

        //线程结束，处理消息
        workHandler = new Handler(mHandlerThread.getLooper()){
            @Override
            public void handleMessage(Message msg) {
                //主线程
                mainHandler.post(new Runnable() {
                    @Override
                    public void run () {
                        if(friends.size() > 0){
                            loading(false);
                            FriendsAdapter friendsAdapter = new FriendsAdapter(friends, FriendListFragment.this);
                            binding.friendsRecyclerView.setAdapter(friendsAdapter);
                            binding.friendsRecyclerView.setVisibility(View.VISIBLE);
                            binding.textErrorMessage.setVisibility(View.INVISIBLE);
                        }else {
                            loading(false);
                            showErrorMessage();
                        }
                    }
                });
            }
        };
    }

    //滑回，会resume，在此复原或刷新内容
    @Override
    public void onResume() {
        super.onResume();
        getFriends();
    }

    //滑走，会Pause，在此复原或刷新内容
    @Override
    public void onPause() {
        super.onPause();
        friends.clear();
    }

    private void getFriends(){
        loading(true);

        FriendListFragment.getFriendsList_Thread getFriendsList_thread = new FriendListFragment.getFriendsList_Thread();
        getFriendsList_thread.start();
    }

    private void showErrorMessage(){
        binding.textErrorMessage.setText(String.format("%s", "Sorry, you don't have any friends QAQ"));
        binding.textErrorMessage.setVisibility(View.VISIBLE);
    }

    private void loading(Boolean isLoading){
        if(isLoading){
            binding.progressBar.setVisibility(View.VISIBLE);
        }else {
            binding.progressBar.setVisibility(View.INVISIBLE);
        }
    }

    class getFriendsList_Thread extends Thread{
        public void run(){
            //线程结束调用workHandler.sendMessage(message);
            //message在此只做线程结束标记作用
            Message message = new Message();
            try {
                User user = ((User)getActivity().getApplicationContext());
                //获取服务器端的输出流
                PrintStream printStream = new PrintStream(user.getSocket().getOutputStream());

                //发送服务端事件
                String msg = "FriendList";
                printStream.println(msg);

                //接受服务端反馈: 用户好友的ID, Name, (State)
                String getMsg = null;
                Scanner scanner = new Scanner(user.getSocket().getInputStream());

                while (scanner.hasNextLine()) {
                    getMsg = scanner.nextLine();
                    if(getMsg.equals("EndOfList")){
                        break;
                    }
                    Friend friend = new Friend();
                    friend.id = getMsg;

                    getMsg = scanner.nextLine();
                    friend.name = getMsg;

                    getMsg = scanner.nextLine();
                    friend.state = getMsg;

                    friends.add(friend);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            workHandler.sendMessage(message);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandlerThread.quit(); // 退出消息循环
        workHandler.removeCallbacks(null); // 防止Handler内存泄露 清空消息队列
    }

    @Override
    public void onUserClicked(Friend friend) {
        Intent intent = new Intent(getActivity().getApplicationContext(), ChatActivity.class);
        intent.putExtra("friend", friend);
        startActivity(intent);
        getActivity().finish();;
    }
}